# -*- coding: utf-8 -*-
"""
@Time ： 2021/6/22 15:54
@Auth ： Mr. royalday 2487625775
@Company ：XXX
@Function ：请输入模块功能描述
"""
from django.http import HttpResponse
from django.shortcuts import render, redirect

from web import models
from utils.tencent.cos import delete_bucket


def setting(request, project_id):
    """
    项目主页-配置页面
    :param request:
    :param project_id: 项目id
    :return:
    """
    return render(request, 'manage/setting.html')


def delete_project(request, project_id):
    """
    删除项目，同时删除cos桶
    :param request:
    :param project_id:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'manage/setting_project_delete.html')
    project_name = request.POST.get('project_name')
    # 如果项目名称写错了或者没传
    if not project_name or project_name != request.tracer.project.name:
        return render(request, 'manage/setting_project_delete.html', {'error': f'项目【{project_name}】不存在'})

    # 如果项目名称写对了
    # 只有项目创建者才可以删除项目
    if request.tracer.user != request.tracer.project.creator:
        return render(request, 'manage/setting_project_delete.html',
                      {'error', f'只有项目创建者【{request.tracer.project.creator}】才可以删除项目'})

    # 1、删除桶：
    # 删除桶内的所有文件
    # 删除桶内的所有碎片文件
    # 删除桶
    bucket_name = request.tracer.project.bucket
    region = request.tracer.project.region
    flag = delete_bucket(bucket=bucket_name, region=region)

    # 2、删除项目
    if not flag:
        return render(request, 'manage/setting_project_delete.html',
                      {'error': f'删除项目对于的桶【{bucket_name}】时出现异常'})

    models.Project.objects.filter(id=project_id).delete()

    # 删除项目后返回到项目列表页面
    return redirect("web:project_list")
